const express = require('express');
// 引入cors模块
const cors = require('cors');
const path = require('path');

const app = express();

// 引入中间件
//所有的中间件都是在服务器下边写，所有的路由都可以用到浏览器
//浏览器先请求，中间件拦截，然后将请求的数据处理解析

// 启动服务器
app.listen(3000, () => {
  console.log('serving is start Do Not Close启动成功');
});

// 使用中间件cors
app.use(
  cors({
    // 允许跨域的服务器地址,可以写多个
    origin: [
      'http://localhost:8081',
      'http://127.0.0.1:8081',
      'http://127.0.0.1:8080',
      'http://localhost:8080',
      'http://127.0.0.1:3000',
      'http://localhost:3000',
    ],
  })
);
// 导入各个路由模块
const userRouter = require('./routes/user');
const busRouter = require('./routes/bus');
const orderRouter = require('./routes/order');
const petRouter = require('./routes/pet');
const dairyRouter = require('./routes/dairy');
const PetuserRouter = require('./routes/PetUser');
const PetBusiness = require('./routes/PetBusiness');
const PetDairy = require('./routes/PetDairy');
const PetOrder = require('./routes/PetOrder');
const PetAdmin = require('./routes/PetAdmin');

const bodyParser = require('express');
app.use(bodyParser.urlencoded({ extended: false }));

// 使用路由
app.use('/user', userRouter);
app.use('/v1/bus', busRouter);
app.use('/order', orderRouter);
app.use('/pet', petRouter);
app.use('/dairy', dairyRouter);
app.use(PetuserRouter);
app.use(PetBusiness);
app.use(PetDairy);
app.use(PetOrder);
app.use(PetAdmin);

// 使用错误处理中间件,拦截所有路由中抛出的错误
app.use((err, req, res, next) => {
  //err 得到的中间件传递过来的错误
  console.log(err);
  //设置http响应的状态码
  res.status(500).send({ code: 500, msg: '服务器端错误' });
});

// 必须在指定静态文件夹之前书写
const history = require('connect-history-api-fallback');
app.use(history());

// 托管静态资源文件夹
app.use(express.static('./public'));
app.use(express.static(path.join(__dirname, 'public')));
